#include "texture.h"

#include "gl.h"

flip_texture
flip_create_texture(unsigned width, unsigned height)
{
	GLint unpack_alignment;
	flip_texture self;
	
	self.width = width;
	self.height = height;
	
	glGetIntegerv(GL_UNPACK_ALIGNMENT, &unpack_alignment);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
		
	glGenTextures(1, &self.id);
	glBindTexture(GL_TEXTURE_2D, self.id);
	glTexImage2D(GL_TEXTURE_2D, 0, 4,
            width, height, 0, GL_RGBA,
            GL_UNSIGNED_BYTE, 0);
            
    flip_check_gl_error();
    
#if 0
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#else
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
#endif
    
    glPixelStorei(GL_UNPACK_ALIGNMENT, unpack_alignment);
    
    return self;
}


void
flip_destroy_texture(flip_texture self)
{
	glDeleteTextures(1, &self.id);
}

void
flip_texture_upload_subimage(flip_texture self, unsigned x, unsigned y, unsigned w, unsigned h, void const* pixels)
{
	glBindTexture(GL_TEXTURE_2D, self.id);
	glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
	
	flip_check_gl_error();
}